package com.ocm.tourism.web;

import java.io.UnsupportedEncodingException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.ocm.tourism.core.domain.Festival;
import com.ocm.tourism.core.service.FestivalService;
import com.ocm.tourism.web.util.FileInfoUtil;

@RequestMapping("/festival")
@Controller
public class FestivalController {

   @Autowired
   FestivalService festivalService;

   @Autowired
   FileInfoUtil fileInfoUtil;

   @InitBinder
   public void initBinder(WebDataBinder binder) {
        binder.initDirectFieldAccess();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

   @RequestMapping(value = "/create", method = RequestMethod.GET)
   public String createForm(Model uiModel) {
      Festival festival = new Festival();
      populateEditForm(uiModel, festival);
      return "festival/create";
   }

   @RequestMapping(value = "/{id}", method=RequestMethod.GET)
   public String show(@PathVariable("id") Long id, Model uiModel) {
      uiModel.addAttribute("itemId", id);
      Festival festival = this.festivalService.findFestival(id);
      populateEditForm(uiModel, festival);
      return "festival/show";
   }

   @RequestMapping(value = "/{id}/update", method=RequestMethod.GET)
   public String update(@PathVariable("id") Long id, Model uiModel) {
      uiModel.addAttribute("itemId", id);
      Festival festival = this.festivalService.findFestival(id);
      populateEditForm(uiModel, festival);
      return "festival/update";
   }
   
   @RequestMapping(produces = "text/html", method=RequestMethod.GET)
   public String list(Model uiModel) {
        List<Festival> festivals = festivalService.findAll();;
        uiModel.addAttribute("festivals", festivals);
       return "festival/list";
   }

   @RequestMapping(method=RequestMethod.POST)
   public String create(@Valid Festival festival, BindingResult bindingResult, Model uiModel) {
       if (bindingResult.hasErrors()){
          populateEditForm(uiModel, festival);
          return "festival/create";
       }
       this.festivalService.save(festival);
       return "redirect:/festival";
   }
   
   @RequestMapping(method=RequestMethod.PUT)
   public String update(@Valid Festival festival, BindingResult bindingResult, Model uiModel) {
       if (bindingResult.hasErrors()){
          populateEditForm(uiModel, festival);
          return "festival/update";
       }
       this.festivalService.save(festival);
       return "redirect:/festival";
   }

   @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
   public String delete(@PathVariable("id") Long id, Model uiModel) {
      this.festivalService.delete(id);
       return "redirect:/festival";
   }
   
   @RequestMapping(value="/view/light", produces = "text/html", method=RequestMethod.GET)
   public String listViewLight(Model uiModel) {
       listView(uiModel);
       return "festival/view/light";
   }
   
   @RequestMapping(value="/view", produces = "text/html", method=RequestMethod.GET)
   public String listView(Model uiModel) {
       List<Festival> festivals = festivalService.findAll();
       Map<String, List<Festival>> groupFestivalsByMonth = new HashMap<String, List<Festival>>();
       Map<String, Map<String, List<Festival>>> groupFestivalsByAddress = new HashMap<String, Map<String, List<Festival>>>();
       List<Festival> festivalsByAddress = new ArrayList<Festival>();
       String lastName = null;
       String lastMonth = null;
       for (Festival festival : festivals){
          if (groupFestivalsByAddress.size() == 0){
             lastName = festival.getAddress();
             groupFestivalsByAddress.put(lastName, groupFestivalsByMonth);
          }else if (!lastName.equalsIgnoreCase(festival.getAddress())){
             lastName = festival.getAddress();
             groupFestivalsByMonth = new HashMap<String, List<Festival>>();
             groupFestivalsByAddress.put(lastName, groupFestivalsByMonth);
          }
          if (lastMonth == null){
             lastMonth = festival.getMonth();
             groupFestivalsByMonth.put(lastMonth, festivalsByAddress);
          }else if (!lastMonth.equalsIgnoreCase(festival.getMonth())){
             lastMonth = festival.getMonth();
             festivalsByAddress = new ArrayList<Festival>(); 
             groupFestivalsByMonth.put(lastMonth, festivalsByAddress);
          }
          festivalsByAddress.add(festival);
       }
       uiModel.addAttribute("festivalsByAddress", groupFestivalsByAddress);
       uiModel.addAttribute("addresses", groupFestivalsByAddress.keySet());
       uiModel.addAttribute("submenuSelected", "tayninhinfo");
       return "festival/view";
   }
   
   void populateEditForm(Model uiModel, Festival festival) {
      uiModel.addAttribute("festival", festival);
   }
   
   String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
      String enc = httpServletRequest.getCharacterEncoding();
      if (enc == null) {
          enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
      }
      try {
          pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
      } catch (UnsupportedEncodingException uee) {}
      return pathSegment;
  }
}
